<template>
  <div>
    <Category :scene="scene" />
    <el-card style="margin:10px 0px">
      <div v-show="scene == 0">
        <el-button @click="addAttr" type="primary" size="default" icon="Plus"
          :disabled="store.c3Id ? false : true">添加属性值</el-button>
        <el-table border style="margin:10px 0px" :data="attrArr">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <el-tag style="margin:5px" v-for="item in row.attrValueList" :key="item.id">{{
                item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{ row }">
              <el-button type="warning" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
              <el-popconfirm :title="`您确定要删除${row.attrName}?`" width="250px" icon="Delete" @confirm='removeAttr(row.id)'>
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input placeholder="请你输入属性名称" v-model="attrParams.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addAttrValue" :disabled="attrParams.attrName ? false : true" type="primary" size="default"
          icon="Plus">添加属性值</el-button>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-table border style="margin:10px 0px" :data="attrParams.attrValueList">
          <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row, $index)" size="small"
                placeholder="请你输入属性值名称" v-model="row.valueName"></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{index }">
              <el-button type="danger" size="small" icon="Delete"
                @click="attrParams.attrValueList.splice(index, 1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" :disabled="attrParams.attrValueList.length > 0 ? false : true"
          @click="save">保存</el-button>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr';
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/type';
import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus'
import useCategoryStore from '@/store/modules/category';
const store = useCategoryStore()

let attrArr = ref<Attr[]>([]);
// 定义card组件内容切换变量
let scene = ref<number>(0);//scene=0,显示table,scene=1,展示添加与修改属性结构

watch(() => store.c3Id, () => {
  attrArr.value = [];
  if (!store.c3Id) return;
  //获取分类的ID
  getAttr()
})
// 获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = store
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code == 200) {
    attrArr.value = result.data
  }
}
// 属性操作
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: store.c3Id,
    categoryLevel: 3,
  })
  scene.value = 1
}
const updateAttr = (row: Attr) => {
  scene.value = 1
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
}
const removeAttr = async(attrId: number) => {
  let result: any = await reqRemoveAttr(attrId);
  if (result.code == 200) {
    ElMessage.success('删除成功')
    getAttr();
  } else {
    ElMessage.error('删除失败')
  }
}
//收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: "",//新增的属性的名字
  attrValueList: [],//新增的属性值数组
  categoryId: '',//三级分类的ID
  categoryLevel: 3,//代表的是三级分类
})

// 属性值操作
let inputArr = ref<any>([]);// 存储对应的组件实例el-input
// 属性值表单失去焦点
const toLook = (row: AttrValue, index: number) => {
  // 非法情况1
  if (row.valueName.trim() == '') {
    // 删除调用对应属性值为空的元素
    attrParams.attrValueList.splice(index, 1);
    ElMessage.error('属性值不能为空')
    return false
  }
  // 非法情况2
  let repeat = attrParams.attrValueList.find((item) => {
    // 把当前失却焦点属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName;
    }
  })
  if (repeat) {
    // 将重复的属性值从数组当中干掉
    attrParams.attrValueList.splice(index, 1)
    ElMessage.error('属性值不能重复')
    return false
  }
  row.flag = false
}
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,// 控制每一个属性值编辑模式与切换模式的切换
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  })
}
const toEdit = (row: AttrValue, index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[index].focus();
  })
}
const save = async () => {
  let result: any = await reqAddOrUpdateAttr(attrParams);
  if (result.code == 200) {
    scene.value = 0
    ElMessage.success(attrParams.id ? '修改成功' : '添加成功')
    getAttr();
  } else {
    ElMessage.error(attrParams.id ? '修改失败' : '添加失败')
  }
}
const cancel = () => {
  scene.value = 0
}
// 路由组件销毁的时候，把仓库分类相关的数据清空
// onBeforeUnmount(() => {
//   store.$reset()
// })
</script>

<style scoped></style>